<template>
  <div>
    <!--面包屑导航区域-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区域-->
    <el-card class="box-card">
      <!--搜索与添加区域-->
      <el-row :gutter="12">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" :clearable="true" @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- stripe 表示隔行变色 -->
      <!--用户列表区域-->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index" label="#" width="40"></el-table-column>
        <el-table-column label="姓名" prop="username" width="80"></el-table-column>
        <el-table-column label="邮箱" prop="email" width="140"></el-table-column>
        <el-table-column label="电话" prop="mobile" width="110"></el-table-column>
        <el-table-column label="角色" prop="role_name" width="100"></el-table-column>
        <el-table-column label="状态" width="70">
          <template slot-scope="scope">
            <!--scope.row 能拿到这行的数据-->
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!--scope.row 能拿到这行的数据  作用域插槽-->
            <!--修改按钮-->
            <el-tooltip effect="dark" content="编辑角色" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">
              </el-button>
            </el-tooltip>
            <!--删除按钮-->
            <el-tooltip effect="dark" content="删除角色" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUserById(scope.row.id)">
              </el-button>
            </el-tooltip>
            <!--分配角色按钮-->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
            </el-tooltip>

          </template>
        </el-table-column>

      </el-table>
      <!--分页区域-->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.currentPage" :page-sizes="[20,40, 60, 80]" :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
      <!--添加用户的对话框-->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="40%" @close="addUserDialogClose">
        <!--内容主体区域-->
        <el-form :model="addUserForm" ref="addUserRef" :rules="addUserRules" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="passsword">
            <el-input v-model="addUserForm.passsword"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phoneNum">
            <el-input v-model="addUserForm.phoneNum"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
        </el-form>
        <!--底部区域-->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!--修改用户的对话框-->
      <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
        <!--内容主体区域-->
        <el-form :model="editUserForm" ref="addUserRef" :rules="addUserRules" label-width="80px">
          <el-form-item label="用户名">
            <el-input v-model="editUserForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phoneNum">
            <el-input v-model="editUserForm.phoneNum"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserForm.email"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo">确 定</el-button>
        </span>
      </el-dialog>
      <!--分配角色对话框-->
      <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleDialogClosed">
        <div>
          <p>当前的用户：{{ userInfo.username  }}</p>
          <p>当前的用户：{{ userInfo.role_name  }}</p>
          <p>分配新角色：
            <el-select v-model="selectedRoleId" clearable placeholder="请选择">
              <el-option v-for="item in rolelist" :key="item.id" :label="item.roleName" :value="item.id">
              </el-option>
            </el-select>

          </p>
        </div>
        <span slot="footer" close="dialog-footer">
          <el-button @click="setRoleDialogVisible=false">取消</el-button>
          <el-button type="primary" @click="saveRoleInfo">确定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
  export default {
    created() {
      this.getUserList()
    },
    data() {

      // 验证邮箱的规则
      var checkEmail = (rule, value, callback) => {
        const regEmail = /^([a-zA-Z0-9_-])+@(a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]))+/
        if (!regEmail.test(value)) {
          //合法的邮箱
          return callback(new Error('请输入合法的邮箱'))
        }
        callback()
      }
      var checkPhone = (rule, value, callback) => {

        const regPhone = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
        if (!regPhone.test(value)) {
          //合法的邮箱
          return callback(new Error('请输入合法的手机号'))
        }
        callback()
      }
      return {
        //这是添加用户的验证规则对象
        addUserRules: {
          //验证登录手机号
          username: [{
              required: true,
              message: '请输入用户名',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 10,
              message: '用户名的长度在3~10个字符之间',
              trigger: 'blur'
            }
          ],
          //验证密码
          passsword: [{
              required: true,
              message: '请输入登录密码',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 15,
              message: '长度为6~15个字符',
              trigger: 'blur'
            }
          ],
          phoneNum: [{
              required: true,
              message: '请输入手机号',
              trigger: 'blur'
            },
            {
              validator: checkPhone,
              trigger: 'blur'
            }
          ],
          email: [{
              required: true,
              message: '请输入邮箱',
              trigger: 'blur'
            },
            {
              validator: checkEmail,
              trigger: 'blur'
            }
          ]
        },

        //获取用户列表的参数对象
        queryInfo: {
          query: '',
          //当前的页数
          pageNum: 1,
          currentPage: 2,
          //当前每页显示多少条数据
          pageSize: 20
        },
        total: 20,
        userlist: [],
        //控制添加对话框的显示与蕴藏
        addDialogVisible: false,
        //控制修改用户对话框的显示与隐藏
        editDialogVisible: false,
        setRoleDialogVisible: false,
        //添加用户的表单数据
        addUserForm: {
          username: '',
          passsword: '',
          phoneNum: '',
          email: ''
        },
        //查询到的用户信息对象
        editUserForm: {
          username: '',
          phoneNum: '',
          email: ''
        },
        //需要被分配角色的用户信息
        userInfo: {},
        //所有的角色数据列表
        rolelist: [],
        selectedRoleId: ''
      }
    },
    methods: {
      async getUserList() {
        // const {
        //   data: res
        // } = await this.$http.get('users', {
        //   parms: this.queryInfo
        // })
        // console.log(res)
        // this.total = res.total
        this.userlist = [{
            id: 1,
            username: '王小虎',
            mobile: '15210325579',
            email: 'rige112@163.com',
            role_name: '超级管理员',
            mg_state: true,
            type: 1
          },
          {
            id: 2,
            username: '王三',
            mobile: '186',
            email: 'rige112@163.com',
            role_name: '管理员',
            mg_state: false,
            type: 1
          },
          {
            id: 3,
            username: '王小虎',
            mobile: '186',
            email: 'rige112@163.com',
            role_name: '超级管理员',
            mg_state: true,
            type: 1
          },
          {
            id: 4,
            username: '王小虎',
            mobile: '186',
            email: 'rige112@163.com',
            role_name: '超级管理员',
            mg_state: false,
            type: 1
          },
          {
            id: 5,
            username: '王小虎',
            mobile: '186',
            email: 'rige112@163.com',
            role_name: '超级管理员',
            mg_state: true,
            type: 1
          }
        ]

      },

      //监听 switch 开关的改变
      async userStateChanged(userinfo) {
        console.log(userinfo)
        // const {
        //   data: res
        // } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
        // if (res.meta.status !== 200) {
        //   userinfo.mg_state = !userinfo.mg_state
        //   return this.$message.error('更新用户识别')
        // }
        // this.$message.success('更新用户状态成功')
      },
      //监听 pageSize 改变的事件
      handleSizeChange(newSize) {
        console.log(newSize)
        this.queryInfo.pageSize = newSize
        // this.getUserList()
      },
      handleCurrentChange(newPage) {
        console.log(newPage)
        this.queryInfo.pageNum = newPage
        // this.getUserList()
      },
      currentPage() {
        this.queryInfo.pageNum = 1
      },
      //重置添加用户对话框
      addUserDialogClose() {
        this.$refs.addUserRef.resetFields()
      },
      //点击按钮，添加新用户
      addUser() {
        this.$message.success('添加用户成功')
        this.addDialogVisible = false;
        this.getUserList()
        // this.$refs.addUserRef.validate(valid=>{
        //   console.log(valid)
        //   if(valid){
        //       //可以发起真正的网络请求
        //     const (res:data)= async this.$http.post('users',this.addUserForm)
        //     if(res.meta.status!==201){
        //       this.$message.error('添加用户失败')
        //     }
        //     this.$message.success('添加用户成功')
        //     this.addDialogVisible=false;
        //     this.getUserList()
        //   }

        // })

      },
      //展示编辑用户的对话框
      async showEditDialog(id) {
        console.log(id)
        this.editDialogVisible = true

        // const {data: res } =await this.$http.get('users/'+id)
        // if(res.meta.status!==200){
        //   return this.$message.error('查询用户信息失败')
        // }
        this.editUserForm.username = 'admin'
        this.editUserForm.phoneNum = '15210325579'
        this.editUserForm.email = 'asdf@qq.com'
      },
      editDialogClosed() {
        this.$refs.addUserRef.resetFields()
      },
      //编辑的验证请求
      editUserInfo() {
        this.editDialogVisible = false
        // this.$refs.addUserRef.validate(async valid=>{
        //   console.log(valid)
        //   if(valid){
        //       //可以发起真正的网络请求
        //     const (res:data)= async this.$http.put('users/'+this.editUserForm.id,{
        //       email:this.editUserForm.email,
        //       phoneNum:this.editUserForm.phoneNum
        //     })
        //     if(res.meta.status!==200){
        //       this.$message.error('更新用户信息失败')
        //     }
        //     this.$message.success('更新用户成功')
        //     this.editDialogVisible=false;
        //     this.getUserList()
        //   }

        // })

      },
      //弹框提示是否删除
      async deleteUserById(id) {
        this.$confirm('此操作将永久删除该用户，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // await { res:data } =this.$http.delete('users/'+id)
          // if(res.meta.status!==200){
          //     return this.$message.info('删除用户失败！')
          // }
          // this.$message.success('删除用户成功')
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          // this.getUserList()

        }).catch(() => {

          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

      },
      //
      async setRole(userInfo) {
        this.userInfo = userInfo
        //在展示对话框之前获取所有的角色列表
        // const { data:res } = await this.$http.get('roles') 
        this.rolelist = [{
            id: '01',
            roleName: '黄金糕'
          },
          {
            id: '02',
            roleName: '双皮奶'
          },
          {
            id: '03',
            roleName: '蚵仔煎'
          },
          {
            id: '04',
            roleName: '龙须面'
          },
          {
            id: '05',
            roleName: '北京烤鸭'
          }
        ]

        this.setRoleDialogVisible = true
      },
      setRoleDialogClosed(){
        this.selectedRoleId=''
      },
      //点击按钮，分配角色
      async saveRoleInfo() {
        if (!this.selectedRoleId) {
          return this.$message.error('请选择要分配的角色！')
        }
        // const {
        //   data: res
        // } = await this.$http.put(`users${this.userInfo.id}/role`, {
        //   rid: this.selectedRoleId
        // })
        // if (res.meta.status !== 200) {
        //   return this.$message.error('更新角色失败！')
        // }
        this.$message.success('更新角色成功！')
        this.getUserList()
        this.setRoleDialogVisible = false
      }


    }
  }
</script>

<style>
  .el-table {
    margin-top: 15px;
    font-size: 12px;
  }
</style>
